# -*- coding: utf-8 -*-

'''
    Temlates rendering stuff here
'''

from onlinebrary.lib.base import *

from onlinebrary.model.agg_data import AggregatedData
from onlinebrary.model.html_data import HtmlData
from onlinebrary.model.feed_data import FeedData

import logging

log = logging.getLogger(__name__)

class Viewer(object):

    def __init__(self):
        pass
        
        
    def parse(self, data):
        content = ""
        if isinstance(data, list) and len(data) > 0:
            for block in data:
                content += self.parse(block)
        elif isinstance(data, Exception):
            content = self.parse_error(data)
        elif isinstance(data, HtmlData):
            content = self.parse_html_info(data)
        elif isinstance(data, FeedData):
            content = self.parse_feed_info(data)
        elif isinstance(data, AggregatedData):
            content = self.parse_aggregated_info(data)
        else:
            log.error('Unknown data type "%s"', type(data))
            content = self.parse_error('Внутренняя ошибка при конвертации :(')

        return content
    
    def parse_error(self, data):
        if isinstance(data, str):
            c.message = data
        elif isinstance(data, Exception):
            c.message = ""
            for msg in data.args:
                c.message += str(msg)
            if 'not well-formed' in c.message:
                c.message += ' <a href="http://feedvalidator.org/">валидатор ↗</a>'
        return render('/error.mako')
        
        
    def parse_feed_info(self, feed_data, is_alone=True):
        c.feed_title = feed_data.title
        c.feed_url = feed_data.url
        
        if is_alone:
            return render('/converter/feed.mako')
        else:
            return render('/converter/html_feed.mako')
        
    def parse_html_info(self, html_info):
        if len(html_info.feeds) > 0:
            c.is_feeds = True
            c.feeds = ""
            for feed in html_info.feeds:
                c.feeds += self.parse_feed_info(feed, False)
        else:
            c.is_feeds = False
            
        c.page_title = html_info.title
        c.url = html_info.url
        
        return render('/converter/html.mako')
        
    def parse_aggregated_info(self, agg_info):
        c.how_much = agg_info.count
        c.search_url = agg_info.source_search
        c.blocks = agg_info.data
        c.agg_name = agg_info.source_name
        
        return render('/aggregator/book_search_results.mako')
                
                    
                    
                    
                    
                    
                    
